package com.ming_za.od_updater.core.window;

import javax.swing.*;

import com.ming_za.od_updater.core.updater.UpdaterManager;
import com.ming_za.od_updater.core.window.page.IPage;

import java.awt.*;

public class PageManager {

    //由于希望该mod初始化尽量靠前，所以无法使用语言文件
    private static final String title = "初梦更新程序";
    public static final  String updatingText = "更新中...";
    public static final  String cancelText = "取消";
    public static final  String checkUpdateText = "检查更新中...";
    public static final  String continueText = "继续启动";
    public static final  String shutdownText = "关闭游戏";
    public static final  String unConnectText = "无法连接至服务器";
    public static final  String failedText = "更新失败";
    public static final  String retryText = "重试";

    private static boolean isInitialized = true;

    private static JPanel panel;
    private static JDialog dialog;

    public static boolean noDisplay = false;

    public static void renderDialog(IPage page) {
        if (GraphicsEnvironment.isHeadless()) {
            new Thread(UpdaterManager::startUpdate).start();
            noDisplay = true;
            return;
        }

        try {
            // 确保在事件分发线程中执行
            if (!EventQueue.isDispatchThread()) {
                EventQueue.invokeLater(()->PageManager.renderDialog(page));
                return;
            }

            // 设置系统外观
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

            // 创建自定义对话框
            dialog = new JDialog((Frame) null, title);
            dialog.setAlwaysOnTop(true); // 关键置顶设置
            dialog.setResizable(false);

            dialog.setLayout(new FlowLayout());

            // 设置窗口内容
            panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

            setPage(page);

            dialog.setContentPane(panel);
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.pack();
            dialog.setSize(300,140);
            dialog.setLocationRelativeTo(null); // 居中显示
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置页面
     * <p>改方法需要在{@link #renderDialog(IPage)}之后调用</p>
     * <p>用于修改页面内容</p>
     * @param page 页面对象
     */
    public static void setPage(IPage page) {

        if (noDisplay){
            return;
        }

        if (!isInitialized) {
            panel.removeAll(); // 移除所有现有组件
        }else {
            isInitialized = false;
        }

        page.renderContent(panel);

        panel.revalidate(); // 重新计算布局
        panel.repaint(); // 重绘面板

    }

    /**
     * 关闭弹窗
     */
    public static void closeDialog(){
        if (!noDisplay && dialog != null) {
            dialog.dispose();
        }
    }
}
